package  
{
	import be.boulevart.events.FLVRecorderEvent;
	import be.boulevart.video.FLVRecorder;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.utils.Timer;
	
	/**
	 * ...
	 * @author db0@qq.com
	 */
	public class VidTest extends Sprite 
	{
		private var vidDisplay:Video = new Video();
		private var tmr:Timer;
		private var recorder:FLVRecorder;
		private var file:File;
		
		public function VidTest() 
		{
			addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			var cam:Camera = Camera.getCamera();
			addChild(vidDisplay);
			vidDisplay.attachCamera(cam);
			vidDisplay.addEventListener(Event.ACTIVATE, starts);
		}
		
		private function starts(e:Event):void 
		{
			trace("=============");
			stage.addEventListener(MouseEvent.CLICK, stopRec);
		}

		private function stopRec(e:MouseEvent):void 
		{
			if(recorder)
			//recorder.stopRecording();
				stopRecording();
			else
				startRecording(10, stage);
		}


		private function startRecording(fps:int,systemManager:Stage):void{
			if(recorder==null){
				recorder=FLVRecorder.getInstance()
			}
			file=File.desktopDirectory.resolvePath("recording.flv");
			recorder.setTarget(file, 640, 480, fps, systemManager);

			if(tmr==null){
				tmr=new Timer(1000/fps)
			}
			tmr.addEventListener(TimerEvent.TIMER, record);
			tmr.start();
		}

		private function record(e:TimerEvent):void {
		 //recorder.captureComponent(this)   //DisplayObject
			 var bmpdata:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
			 bmpdata.draw(this);
			 recorder.saveFrame(bmpdata)  //Bitmapdata
			 //recorder. saveSmoothedBitmapFrame(bmp)  //Bitmap
			 //recorder. saveSmoothedFrame(bmpdata)  //Bitmapdata
		}

		private function stopRecording():void{
			tmr.stop();
			//when saving is done
			recorder.addEventListener(FLVRecorderEvent.FLV_CREATED, fileMade);
			//when saving starts
			recorder.addEventListener(FLVRecorderEvent.FLV_START_CREATION, startCreatingFLV);
			recorder.stopRecording();
		}

		private function fileMade(e:FLVRecorderEvent):void 
		{
			trace("com",e.type);
			//recorder.
			//var fileStream:FileStream = new FileStream();
			//fileStream.writeBytes();
			//file
		}

		private function startCreatingFLV(e:FLVRecorderEvent):void{
			recorder.addEventListener(FLVRecorderEvent.PROGRESS, onFLVCreationProgress);
		}

		private function onFLVCreationProgress(e:FLVRecorderEvent):void {
			trace(e.progress);
			 //e.progress: percent complete (0 to 1)
			 //pbSaving: ProgressBar component in Flex
			 //pbSaving.setProgress(e.progress,1)
		}
	}

}